package cn.edu.xmu.orderpayment.order.dao;

import cn.edu.xmu.oomall.core.util.Common;
import cn.edu.xmu.oomall.core.util.ReturnNo;
import cn.edu.xmu.oomall.core.util.ReturnObject;
import cn.edu.xmu.orderpayment.order.mapper.OrderItemPoMapper;
import cn.edu.xmu.orderpayment.order.mapper.OrderPoMapper;
import cn.edu.xmu.orderpayment.order.model.bo.Order;
import cn.edu.xmu.orderpayment.order.model.bo.OrderItem;
import cn.edu.xmu.orderpayment.order.model.enums.OrderState;
import cn.edu.xmu.orderpayment.order.model.po.OrderItemPo;
import cn.edu.xmu.orderpayment.order.model.po.OrderItemPoExample;
import cn.edu.xmu.orderpayment.order.model.po.OrderPo;
import cn.edu.xmu.orderpayment.order.model.po.OrderPoExample;
import cn.edu.xmu.orderpayment.order.model.retvo.SimpleOrderInfoRetVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.List;

import static cn.edu.xmu.privilegegateway.annotation.util.Common.cloneVo;
import static cn.edu.xmu.privilegegateway.annotation.util.Common.setPoModifiedFields;

/**
 * @author YuJie
 * @date 2021-12-02
 */
@Repository
public class OrderDao {

    private Logger logger = LoggerFactory.getLogger(OrderDao.class);

    @Autowired
    private OrderPoMapper orderPoMapper;

    @Autowired
    private OrderItemPoMapper orderItemPoMapper;

    public  ReturnObject getOrderByOrderSn(String orderSn){
        try{
            OrderPoExample oe=new OrderPoExample();
            OrderPoExample.Criteria cr=oe.createCriteria();
            cr.andOrderSnEqualTo(orderSn);
            List<OrderPo> pos=orderPoMapper.selectByExample(oe);
            if(pos==null||pos.size()==0)return new ReturnObject(ReturnNo.RESOURCE_ID_NOTEXIST);
            return new ReturnObject<>(pos.get(0));
        }
        catch (Exception e){
            logger.error(e.getMessage());
            return new ReturnObject(ReturnNo.INTERNAL_SERVER_ERR, e.getMessage());
        }
    }

    public  ReturnObject getOrderByPid(Long pid){
        try{
            OrderPoExample oe=new OrderPoExample();
            OrderPoExample.Criteria cr=oe.createCriteria();
            cr.andPidEqualTo(pid);
            List<OrderPo> pos=orderPoMapper.selectByExample(oe);
            if(pos==null||pos.size()==0)return new ReturnObject(ReturnNo.RESOURCE_ID_NOTEXIST);
            return new ReturnObject<>(pos);
        }
        catch (Exception e){
            logger.error(e.getMessage());
            return new ReturnObject(ReturnNo.INTERNAL_SERVER_ERR, e.getMessage());
        }
    }



    /**
     * 买家查询自己的订单概要
     * 查询条件：订单编号，状态，开始时间，结束时间，页码，页数
     * 不返回已被逻辑删除的订单，按照时间倒序
     *
     * 利用Mapper的select和PoExample配合
     * @return
     */
    public ReturnObject searchMyselfOrders(Long loginUserId, String orderSn, ZonedDateTime beginTime,
                                           ZonedDateTime endTime, Integer state, Integer page, Integer pageSize){
        try {
            OrderPoExample example = new OrderPoExample();
            OrderPoExample.Criteria criteria = example.createCriteria();
            criteria.andCustomerIdEqualTo(loginUserId);
            criteria.andBeDeletedEqualTo(Byte.valueOf("0"));
            if (orderSn != null) {
                criteria.andOrderSnEqualTo(orderSn);
            }
            if (state != null) {
                if(state==200){
                    criteria.andStateGreaterThanOrEqualTo(200);
                    criteria.andStateLessThan(300);
                }
                else {
                    criteria.andStateEqualTo(state);
                }
            }
            if (beginTime != null) {
                criteria.andGmtCreateGreaterThanOrEqualTo(beginTime.withZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime());
            }
            if (endTime != null) {
                criteria.andGmtCreateLessThanOrEqualTo(endTime.withZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime());
            }
            PageHelper.startPage(page,pageSize);
            List<OrderPo> list = orderPoMapper.selectByExample(example);
            list.sort( (order1, order2) -> order2.getGmtCreate().compareTo(order1.getGmtCreate()) );
            PageInfo<OrderPo> pageInfo = new PageInfo<>(list);
            ReturnObject returnObject = new ReturnObject(pageInfo);
            return Common.getPageRetVo(returnObject, SimpleOrderInfoRetVo.class);

        } catch (Exception e) {
            logger.error(e.getMessage());
            return new ReturnObject(ReturnNo.INTERNAL_SERVER_ERR, e.getMessage());
        }
    }

    public ReturnObject searchShopOrders(Long shopId, Long customerId, String orderSn,
                                         ZonedDateTime beginTime, ZonedDateTime endTime, Integer page, Integer pageSize){
        try {
            OrderPoExample example = new OrderPoExample();
            OrderPoExample.Criteria criteria = example.createCriteria();
            if (shopId != 0) {
                criteria.andShopIdEqualTo(shopId);
            }
            if (orderSn != null) {
                criteria.andOrderSnEqualTo(orderSn);
            }
            if (customerId != null) {
                criteria.andCustomerIdEqualTo(customerId);
            }
            if (beginTime != null) {
                criteria.andGmtCreateGreaterThanOrEqualTo(beginTime.withZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime());
            }
            if (endTime != null) {
                criteria.andGmtCreateLessThanOrEqualTo(endTime.withZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime());
            }
            PageHelper.startPage(page,pageSize);
            List<OrderPo> list = orderPoMapper.selectByExample(example);
            list.sort( (order1, order2) -> order2.getGmtCreate().compareTo(order1.getGmtCreate()) );
            PageInfo<OrderPo> pageInfo = new PageInfo<>(list);
            ReturnObject returnObject = new ReturnObject(pageInfo);
            return Common.getPageRetVo(returnObject, SimpleOrderInfoRetVo.class);

        } catch (Exception e) {
            logger.error(e.getMessage());
            return new ReturnObject(ReturnNo.INTERNAL_SERVER_ERR, e.getMessage());
        }
    }

    /**
     * @author YuJie
     * @date 2021-12-10
     */
    public ReturnObject createOrder(Order order) {
        try{
            OrderPo po=cloneVo(order,OrderPo.class);
            orderPoMapper.insertSelective(po);
            return new ReturnObject(po);
        }
        catch (Exception e){
            logger.error(e.getMessage());
            return new ReturnObject(ReturnNo.INTERNAL_SERVER_ERR, e.getMessage());
        }
    }


    /**
     * 根据id返回订单
     * @return
     */
    public ReturnObject getOrder(Long orderId) {
        try{
            OrderPo orderPo = orderPoMapper.selectByPrimaryKey(orderId);
            if(orderPo==null){
                return new ReturnObject(ReturnNo.RESOURCE_ID_NOTEXIST,"该订单不存在");
            }
            Order order = cloneVo(orderPo,Order.class);//根据PO创建BO对象
            return new ReturnObject(order);
        }
        catch (Exception e){
            logger.error(e.getMessage());
            return new ReturnObject(ReturnNo.INTERNAL_SERVER_ERR, e.getMessage());
        }
    }

    /**
     * 根据传入的Bo修改Order
     * @return
     * @creator liuyunlong
     */
    public ReturnObject updateOrder(Order order,Long userId, String userName) {
        try{
            OrderPo orderPo = cloneVo(order,OrderPo.class);
            setPoModifiedFields(orderPo, userId, userName);
            orderPoMapper.updateByPrimaryKeySelective(orderPo);
            return new ReturnObject(orderPoMapper.selectByPrimaryKey(orderPo.getId()));
        }catch (Exception e){
            logger.error(e.getMessage());
            return new ReturnObject(ReturnNo.INTERNAL_SERVER_ERR, e.getMessage());
        }
    }



    public ReturnObject getOrderByGrouponActivityId(Long grouponActivityId){
        try {
            OrderPoExample example=new OrderPoExample();
            OrderPoExample.Criteria criteria=example.createCriteria();
            criteria.andGrouponIdEqualTo(grouponActivityId);
            List<OrderPo> orderPos = orderPoMapper.selectByExample(example);
            if(orderPos.size()==0){
                return new ReturnObject(ReturnNo.RESOURCE_ID_NOTEXIST,"没有此团购活动");
            }
            return new ReturnObject(orderPos);
        }
        catch (Exception exception){
            return new ReturnObject(ReturnNo.INTERNAL_SERVER_ERR,exception.getMessage());
        }
    }


    public ReturnObject<List> getOrderItemsByOrderId(Long orderId) {
        try{
            OrderItemPoExample example=new OrderItemPoExample();
            OrderItemPoExample.Criteria criteria=example.createCriteria();
            criteria.andOrderIdEqualTo(orderId);
            List<OrderItemPo> list = orderItemPoMapper.selectByExample(example);
            return new ReturnObject(list);
        }catch (Exception e){
            logger.error(e.getMessage());
            return new ReturnObject(ReturnNo.INTERNAL_SERVER_ERR, e.getMessage());
        }
    }

    public ReturnObject updateOrderItem(OrderItemPo orderItemPo){
        try{
            orderItemPoMapper.updateByPrimaryKeySelective(orderItemPo);
            return new ReturnObject<>();
        }
        catch (Exception e){
            logger.error(e.getMessage());
            return new ReturnObject(ReturnNo.INTERNAL_SERVER_ERR, e.getMessage());
        }
    }


    public ReturnObject createOrderItem(OrderItem orderItem){
        try{
            OrderItemPo po=cloneVo(orderItem,OrderItemPo.class);
            orderItemPoMapper.insertSelective(po);
            return new ReturnObject(po);
        }
        catch (Exception e){
            logger.error(e.getMessage());
            return new ReturnObject(ReturnNo.INTERNAL_SERVER_ERR, e.getMessage());
        }
    }


    public ReturnObject<OrderItem> getOrderItemById(Long id) {
        try{
            OrderItemPo po=orderItemPoMapper.selectByPrimaryKey(id);
            if(po==null)return new ReturnObject<>(ReturnNo.RESOURCE_ID_NOTEXIST,"该订单明细不存在");
            return new ReturnObject<>(cloneVo(po,OrderItem.class));
        }catch (Exception e){
            logger.error(e.getMessage());
            return new ReturnObject(ReturnNo.INTERNAL_SERVER_ERR, e.getMessage());
        }
    }

}
